<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */

namespace app\api\controller\android\v8;


use think\Cache;
use think\Controller;
use app\api\model\Authority;
use think\db;
use think\Request;
use app\api\model\OrderModel;

class User extends Controller
{
    protected $model;
    protected $us;
    
    public function _initialize()
    {
        $this->model=new Authority();
        $this->us   =$this->model->check(1);
    }
    
    /**
     * 修改手机号
     */
    public function reset_mobile()
    {
        $data=$this->model->post(['code', 'new_mobile']);
        if (!is_mobile($data['new_mobile'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        $s_verify=Cache::get(md5($data['new_mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date([], 300, '验证码错误');
        }
        Cache::clear(md5($data['new_mobile']));
        $user=self::$user;
        if (db('user')->where(['mobile'=>$data['new_mobile'], 'status'=>['in', '0,1,2']])->find()) {
            r_date([], 300, '该手机号已注册用户端，请重新选择手机号');
        }
        $res=db('user')->where(['user_id'=>$user['user_id']])->update(['mobile'=>$data['new_mobile']]);
        if ($res !== false) {
            r_date();
        }
        r_date([], 300, '修改失败，请刷新后重试');
    }
    
    public function index(OrderModel $orderModel)
    {
        $retrun   =db('user')->join('store st', 'st.store_id=user.store_id', 'left')->field('user.user_id,user.work_tag,user.mobile,user.username,user.avatar,user.sex,user.state,st.store_name,st.store_id,user.number,user.reserve')->where(['user_id'=>$this->us['user_id']])->find();
        $BeginDate=date('Y-m-01', strtotime(date("Y-m-d", time())));
        $starttime=strtotime($BeginDate);
        $enttime  =strtotime(date('Y-m-d', strtotime("$BeginDate +1 month -1 day")));
        $quantity =db('order')->where(['created_time'=>['between', [$starttime, $enttime]], 'assignor'=>$this->us['user_id']])->select();//本月接单量
        
        
        $list=$m=$orderModel->table('order')->alias('a')->field('concat(p.province,c.city,u.county,a.addres) as  addres,a.contacts,co.con_time,a.order_id,a.state,a.assignor,go.title')->join('province p', 'a.province_id=p.province_id', 'left')->join('city c', 'a.city_id=c.city_id', 'left')->join('county u', 'a.county_id=u.county_id', 'left')->join('user us', 'a.assignor=us.user_id', 'left')->join('goods_category go', 'a.pro_id=go.id', 'left')->join('contract co', 'a.order_id=co.orders_id', 'left')->where('a.assignor', $this->us['user_id'])->whereBetween('co.con_time', [$starttime, $enttime])->order('co.con_time desc')->whereBetween('a.state', [4, 7])->select();
        foreach ($list as $k=>$key) {
            $mouth=$orderModel->offer($key['order_id']);
            //签约金额
            $list[$k]['amount']=sprintf('%.2f', $mouth['amount']);
        }

        $amount=sprintf('%.2f', array_sum(array_column($list, 'amount')));

        $zeng              =array_sum(array_column((new Financial)->zeng($starttime, $enttime, $this->us['user_id']), 'turnover'));
   
        $jian              =array_sum(array_column((new Financial)->jian($starttime, $enttime, $this->us['user_id']), 'turnover'));
        $tui               =array_sum(array_column((new Financial)->tui($starttime, $enttime, $this->us['user_id']), 'turnover'));

        $ye                =sprintf('%.2f', $amount + $zeng - $jian - $tui);
        $retrun['quantity']=count($quantity);
        $retrun['signing'] =$ye;
        $retrun['volume']  =(new Financial)->TurnoverRate('ss');
        $retrun['bankCard']=\db('bank_card')->where(['user_id'=>$this->us['user_id'], 'binding_uid'=>$this->us['user_id']])->where('category',1)->value('bank_card_number');
        
        $work_tag=empty($retrun['work_tag'])? [0, 0, 0, 0] : explode(',', $retrun['work_tag']);
        foreach ($work_tag as $k=>$value) {
            $k=$k + 1;
            switch ($value) {
                case 0:
                    $value='https://images.yiniao.co/Icon/shopowner/small/' . $k . '-grey-small.png';
                    break;
                case 1:
                    $value='https://images.yiniao.co/Icon/shopowner/small/' . $k . '-small.png';
                    break;
            }
            $date[]=$value;
        }
        $retrun['work_tag']=$date;
        
        r_date($retrun, 200, '获取成功');
    }
    
    public function Icon()
    {
        $work_tag=db('user')->where(['user_id'=>$this->us['user_id']])->value('work_tag');
        $work_tag=empty($work_tag)? [0, 0, 0, 0] : explode(',', $work_tag);
        foreach ($work_tag as $k=>$value) {
            
            switch ($k) {
                case 0:
                    $data['title']='建筑渗漏水维修专家';
                    break;
                case 1:
                    $data['title']='旧房改造类专家';
                    break;
                case 2:
                    $data['title']='墙面维修专家';
                    break;
                case 3:
                    $data['title']='室内渗漏水维修专家';
                    break;
            }
            $k=$k + 1;
            switch ($value) {
                case 0:
                    $data['img']='https://images.yiniao.co/Icon/shopowner/big/' . $k . '-grey.png';
                    break;
                case 1:
                    $data['img']='https://images.yiniao.co/Icon/shopowner/big/' . $k . '.png';
                    break;
            }
            $date[]=$data;
        }
        
        
        r_date($date, 200, '获取成功');
    }
    
    /**
     * 修改我的状态
     */
    public function state()
    {
        $data=$this->model->post(['state']);
        //店长在线时长统计
        db('online')->insertGetId(['user_id'=>$this->us['user_id'], 'startTime'=>time(), 'type'=>$data['state'], 'time'=>time()]);
        
        $res=db('user')->where(['user_id'=>$this->us['user_id']])->update(['state'=>$data['state']]);
        
        if ($res) {
            r_date([], 200);
        }
        r_date([], 300, '状态修改失败，请刷新后重试');
    }
    
    /**
     * 修改资料
     * invoice_type
     */
    public function edit()
    {
        $data=$this->model->post(['avatar']);
        $res =db('user')->where(['user_id'=>$this->us['user_id']])->update(['avatar'=>$data['avatar'],]);
        if ($res !== false) {
            r_date([], 200);
        }
        r_date([], 300, '编辑失败，请刷新后重试');
    }
    
    
    public function Article()
    {
        $result=send_post(U_SRC . "/support/v1.article/all", []);
        
        
        return r_date(json_decode($result, true), 200);
    }
    
    public function Article_list()
    {
        $data  =$this->model->post(['category_id', 'limit', 'page']);
        $result=send_post(U_SRC . "/support/v1.article/lists", $data);
        
        return r_date(json_decode($result, true), 200);
    }
    
    /*
     * 免打扰
     */
    public function disturb()
    {
        $this->model->post(['type']);
        db('user')->where('user_id', $this->us['user_id'])->update(['disturb'=>2]);
        r_date([], 200);
    }
    
    /*
     * 获取地理位置
     */
    public function lat()
    {
        $data=$this->model->post(['lat', 'lng']);
        db('user')->where('user_id', $this->us['user_id'])->update(['lat'=>$data['lat'], 'lng'=>$data['lng']]);
        r_date(null, 200);
    }
    
    /*
     * 免打扰
     */
    public function about()
    {
        $da=db('about')->find();
        r_date($da, 200);
    }
    
    public function url()
    {
        $da['url']='http://public.yiniaoweb.com/static/help/storemanage/';
        r_date($da, 200);
    }
    
    /*
     * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
     * 30  费用报销 31 主材费用报销，32返工费用报销 33 常规材料  34 采购材料  35 领用申请
     */
    public function message()
    {
        
        $message=db('message')->field('type,content,order_id,already,id')->where(['user_id'=>$this->us['user_id']])->limit(0, 3)->orderRaw('already=1 desc,time desc')->select();
        $data   =[
            'data'=>$message,
                  'newOrders'=>db('message')->where(['user_id'=>$this->us['user_id'], 'type'=>['in', '2,3,4,6,45'], 'already'=>1])->count(),// 订单提醒
                  'approval'=>db('message')->where(['user_id'=>$this->us['user_id'], 'type'=>['in', '30,31,32,33,34,35'], 'already'=>1])->count(),// 审批提醒
//                  'Material'=>db('message')->where(['type'=>['in', '34,33'],'already'=>1, 'user_id'=>$this->us['user_id']])->count(),//
                  'system'=>db('message')->where(['type'=>1, 'already'=>1, 'user_id'=>$this->us['user_id']])->count(),//系统消息
                  'unread'=>db('message')->where(['user_id'=>$this->us['user_id'], 'already'=>1])->count(),//未读消息
                  
            ];
        r_date($data, 200);
    }
    
    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_list()
    {
        //0全部1系统2订单3收款5公司通知7未读
        $data=$this->model->post(['type', 'page'=>1, 'limit'=>10, 'title']);
        $me  =db('message');
        if (isset($data['title']) && $data['title'] != '') {
            $map['content']=['like', "%{$data['title']}%"];
            $me->where($map);
        }
        if ($data['type'] == 2) {
            $me->where(['type'=>['in', '3,4,6,45']]);
        } elseif ($data['type'] == 7) {
            $me->where(['already'=>1]);
        } elseif ($data['type'] == 5) {
            $me->where(['type'=>$data['type']]);
        } elseif ($data['type'] == 1) {
            $me->where(['type'=>$data['type']]);
        }elseif($data['type'] == 22){
            $me->where(['type'=>['in', '30,31,32']]);
        }elseif ($data['type'] == 23){
            $me->where(['type'=>['in', '33,34,35']]);
        }
        $message=$me->where(['user_id'=>$this->us['user_id']])->field('id,type,content,order_id,already')->orderRaw('already=1 desc,time desc')->page($data['page'], $data['limit'])->select();
        r_date($message, 200);
    }
    /*
     * 审批里面的类型
     */
    public function ApprovalType(){
        $data=$this->model->post(['type']);
        if($data['type']==2){
            $data=[
                [
                    'name'=>'全部',
                    'type'=>0,
                    'jump'=>0,
                ],
                [
                    'name'=>'订单提醒',
                    'type'=>2,
                    'jump'=>0,
                ],[
                    'name'=>'收款预警提醒',
                    'type'=>45,
                    'jump'=>0,
                ]
            ];
        }else{
            $data=[
                [
                    'name'=>'全部',
                    'type'=>0,
                    'jump'=>0,
                ],[
                    'name'=>'费用报销',
                    'type'=>30,
                    'jump'=>0,
                ],[
                    'name'=>'主材费用报销',
                    'type'=>31,
                    'jump'=>0,
                ],[
                    'name'=>'材料常规申请（常规）',
                    'type'=>33,
                    'jump'=>0,
                ],[
                    'name'=>'返工费用报销',
                    'type'=>32,
                    'jump'=>0,
                ],[
                    'name'=>'材料申请（采购）',
                    'type'=>34,
                    'jump'=>0,
                ],[
                    'name'=>'材料领用',
                    'type'=>35,
                    'jump'=>0,
                ]

            ];
        }
        r_date($data, 200);
    }
    /*
   * /**30  费用报销 31 主材费用报销，32返工费用报销 33 常规材料  34 采购材料
     * 费用报销内容
     */

    public function message_listApproval()
    {

        $data=$this->model->post(['type','mainType','page', 'limit']);

        $me  =db('message');
        if (isset($data['title']) && $data['title'] != '') {
            $map['content']=['like', "%{$data['title']}%"];
            $me->where($map);
        }
        if($data['mainType']==2){
            if ($data['type']  !=0 ) {
                if($data['type']  ==2){
                    $me->where(['type'=>['in', '3,4,6']]);
                }else{
                    $me->where(['type'=>$data['type']]);
                }

            }else{
                $me->whereIn('type',[3,4,6,2,45]);
            }
        }else{
            if ($data['type']  !=0 ) {
                $me->where(['type'=>$data['type']]);
            }else{
                $me->whereIn('type',[30,31,32,33,34,35]);
            }
        }

        $message=$me->where(['user_id'=>$this->us['user_id']])->field('id,type,content,order_id,already,FROM_UNIXTIME(time,"%Y-%m-%d %H:%i:%s")')->orderRaw('already=1 desc,time desc')->page($data['page'], $data['limit'])->select();
        foreach ($message as $k=> $value){
            if(!empty($value['order_id']) && $value['type']==45){
                $order= db('order')
                    ->field('order.contacts,order.telephone,concat(p.province,c.city,y.county,order.addres) as addres,sum(payment.material+payment.agency_material) as sum,count(payment_id) as count')
                    ->join('user u', 'order.assignor=u.user_id', 'left')
                    ->join('province p', 'order.province_id=p.province_id', 'left')
                    ->join('city c', 'order.city_id=c.city_id', 'left')
                    ->join('county y', 'order.county_id=y.county_id', 'left')
                    ->join('payment', 'order.order_id=payment.orders_id and payment.cleared_time >0', 'left')
                    ->where('order.order_id',$value['order_id'])
                    ->find();

                $order['collection']=$money = OrderModel::offer($value['order_id'])['amount'];
            }else{
                $order=null;
            }
            $message[$k]['order']=$order;
        }
        r_date($message, 200);
    }
    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_info()
    {
        $data           =$this->model->post(['id']);
        $message        =db('message')->where('id', $data['id'])->field('type,content,order_id,already,time')->find();
        $message['time']=date('Y-m-d H:i:s',$message['time']);
        if ($message['already'] != 0) {
            db('message')->where('id', $data['id'])->update(['already'=>0, 'have'=>time()]);
        }
        
        r_date($message, 200);
    }
    
    /*
     * 储备店长
     */
    public function reserve()
    {
        $data  =$this->model->post();
        $chanel=db('user')->field('user.number,user.username,user.mobile,user.lat,user.lng,user.user_id');
        if (isset($data['username']) && $data['username'] != '') {
            $chanel->where(['user.username'=>['like', "%{$data['username']}%"]]);
        }
        $list=$chanel->where(['status'=>0, 'reserve'=>2, 'store_id'=>$this->us['store_id']])->order('status')->select();
        r_date($list, 200);
    }
    
    /**
     * 获取后台客户注册的
     */
    public function jp()
    {
        $message=db('admin')->field('username,logo,admin_id')->where(['status'=>0, 'jp'=>1])->select();
        r_date($message, 200);
    }
    
    /**
     * 店铺
     * invoice_type
     */
    public function store()
    {
        $res=db('store')->field('store_id,store_name')->select();
        
        r_date($res, 200);
        
        
    }
    
    /**
     *工种
     * invoice_type
     */
    public function workType()
    {
        $res=Db::connect(config('database.db2'))->table('app_work_type')->whereNull('deleted_at')->where('status', 1)->field('id,title')->select();
        
        r_date($res, 200);
    }
    
    /*
     * 银行卡添加
     */
    public function bankCard()
    {
        
        $bank_card=\db('bank_card')->where(['user_id'=>$this->us['user_id'], 'binding_uid'=>$this->us['user_id']])->where('category',1)->field('bank_card_number as bankCardNumber,account_name as accountName,bank_of_deposit as bankOfDeposit,bank_id as bankId,bank')->find();
        if (empty($bank_card)) {
            $list=['bankCardNumber'=>'', 'bankOfDeposit'=>'', 'bankId'=>(int)0, 'accountName'=>''];
        } else {
            $list=$bank_card;
        }
        r_date($list, 200);
    }
    
    public function addBankCard()
    {
        $data=Request::instance()->post();
        
//        if (!check_bankCard($data['bankCardNumber'])) {
//            r_date(null, 300, '请输入正确的银行卡号');
//        }
        $count=db('bank_card')->where(['bank_card_number'=>$data['bankCardNumber']])->count();
        if ($count > 0) {
            r_date(null, 300, '请勿重复录入');
        }
        if (isset($data['id']) && !empty($data['id']) != 0) {
            $res=db('bank_card')->where('bank_id', $data['id'])->where('category',1)->update(['account_name'=>$data['accountName'], 'bank_card_number'=>$data['bankCardNumber'], 'bank_of_deposit'=>$data['bankOfDeposit'],'bank'=>$data['bank'],'revision_time'=>time()]);
        } else {
          
            $res=db('bank_card')->insertGetId(['user_id'=>$this->us['user_id'], 'account_name'=>$data['accountName'], 'bank_card_number'=>$data['bankCardNumber'], 'bank_of_deposit'=>$data['bankOfDeposit'], 'type'=>2, 'creation_time'=>time(), 'category'=>1, 'remarks'=>'店长', 'binding_uid'=>$this->us['user_id'],'bank'=>$data['bank']]);
        }
        if ($res) {
            r_date($data['bankCardNumber'], 200);
        } else {
            r_date(null, 300);
        }
    }
    
    public function collectionOtherAdd()
    {
        $data =Request::instance()->post();
        $count=db('bank_card')->where(['bank_card_number'=>$data['bankCardNumber']])->count();
        if ($count > 0) {
            r_date(null, 300, '请勿重复录入');
        }
        //        if (!check_bankCard($data['bankCardNumber'])) {
        //            r_date(null, 300, '请输入正确的银行卡号');
        //        }
        
        $res=db('bank_card')->insertGetId(['user_id'=>$this->us['user_id'], 'account_name'=>$data['accountName'], 'bank_card_number'=>$data['bankCardNumber'], 'bank_of_deposit'=>$data['bankOfDeposit'], 'type'=>$data['type'], 'creation_time'=>time(), 'category'=>1, 'remarks'=>$data['remarks'],'bank'=>$data['bank']]);
        
        if ($res) {
            $data['bankId']=$res;
            r_date($data, 200);
        } else {
            r_date(null, 300);
        }
    }
    
    /*
     * val bankCardNumber: String?,
val accountName: String?,
val bankOfDeposit: String?,
val remarks: String?,
val type: String?,
val bankId: Int?
     */
    public function searchBank()
    {
        $data=Request::instance()->post();
        $res =db('bank_card')->where(function($query) use ($data){
            if ($data['accountName']  != '') {
                $query->whereOr('bank_card_number', 'Like', "%{$data['accountName']}%")->whereOr('account_name', 'Like', "%{$data['accountName']}%");
            }
          
        })->field('bank_card_number as bankCardNumber,account_name as accountName,bank_of_deposit as bankOfDeposit,bank_id as bankId,remarks')->select();
       
        r_date($res, 200);
        
    }
    
    /*
     * 最近使用的
     */
    public function searchLatelBank()
    {
     
        $res=db('reimbursement_relation')
            ->join('reimbursement', 'reimbursement_relation.reimbursement_id=reimbursement.id', 'left')
            ->Join('bank_card', 'bank_card.bank_id=reimbursement_relation.bank_id', 'left')
            ->where('reimbursement.user_id', $this->us['user_id'])
            ->where('reimbursement.type', 1)
            ->where('reimbursement.classification', 'neq',4)
            ->field('bank_card.bank_card_number as bankCardNumber,bank_card.remarks,bank_card.account_name as accountName,bank_card.bank_of_deposit as bankOfDeposit,bank_card.bank_id as bankId')
            ->limit(0, 3)
            ->group('bank_card.bank_card_number')
            ->order('reimbursement.id desc')
            ->select();
        r_date($res, 200);
        
    }
    
    
}